<?php

class HSql {

	function __construct() { }
	
	function doProc($proc_name, $proc_params) {
		$params = '';
		for ($i = 0; $i < count($proc_params); $i++) {
			if ($i < count($proc_params) - 1)
				$params .= "'".$proc_params[$i]."'".',';
			else 
				$params .= "'".$proc_params[$i]."'";				
		}
				
		$query = "CALL ".$proc_name."(". $params .")";
		try {
			mysql_query($query);
		}
		catch (Exception $ex) {
			throw new Exception($ex->getMessage());
		}
	}
	
	function doView($view_name, $condition = null) {		
		$query = "SELECT * FROM ".$view_name."";		
		if ($condition != null) $query .= ' '.$condition;
		$result = mysql_query($query);
		
		$arr = array();
		try {
			while ($rows = mysql_fetch_assoc($result)) {
				$arr[] = $rows;
			}		
		}
		catch (Exception $ex) {
			throw new Exception($ex->getMessage());
		}
		
		return $arr;		
	}
	
	function doQuery($query) {
		try {
			$result = mysql_query($query) or die(mysql_error());
		}
		catch (Exception $ex) {
			throw new Exception($ex->getMessage());
		}
		
		return $result;
	}
	
	function fetch2Array($data){
		$vals = array();
		while ($row = @mysql_fetch_assoc($data)) {
			$vals[] = $row;
		}
		
		if (count($vals) != 0)
			return $vals;
		else 
			return array();
	}
	
	
	/**
	 * getData will return in array results from the query
	 *
	 * @param $table: the table name to access
	 * @param $properties: where, order, group clause for examples
	 */
	function getData($table,$properties = null,$error = null){
		$query="SELECT * FROM ".$table." ".$properties;
		$result = mysql_query($query);
		if($result == false)
			if($error != null){
				echo ("<br>Failed to execute the query!<br>");
				//if($error == 1) 
				echo mysql_error();
				return false;
			}
		return $result;
	}
	
	function getFieldById($table, $field, $id) {		
		try {
			$a = HSql::fetch2Array(HSql::getData($table, "WHERE id = '$id'"));
			if (count($a) == 0) throw new Exception($ex);
			else return $a[0][$field];
		}		
		catch (Exception $ex) {
			echo $ex->getMessage();
		}
	}
	
	function isRecordExist($table, $field, $value) {
		$a = HSql::fetch2Array(HSql::getData($table, "WHERE ".$field." = '$value'"));
		if (count($a) == 0) return false;
		else return true;
	}	
}

?>